package com.superarai.portal.action.admin;

import javax.annotation.Resource;

import org.seasar.framework.util.StringUtil;
import org.seasar.struts.annotation.ActionForm;
import org.seasar.struts.annotation.Execute;

import com.superarai.portal.dto.LoginInfoDto;
import com.superarai.portal.entity.UserInfo;
import com.superarai.portal.enums.Config;
import com.superarai.portal.form.LoginForm;
import com.superarai.portal.service.impl.UserInfoService;
import com.superarai.portal.util.Assertion;

public class LoginAction {
	
	@Resource
	@ActionForm
	public LoginForm loginForm;
	
	@Resource
	protected UserInfoService userInfoService;
	
	@Resource
	protected LoginInfoDto loginInfoDto;
	
	private static final String LOGIN_PAGE_URL = Config.Page.LOGIN.getURL();
	private static final String REDIRECT_LOGIN_PAGE = LOGIN_PAGE_URL + "?redirect=true";
	
	@Execute(validator = false)
	public String index() {
		if(loginInfoDto.isLogin())
			return "/?redirect=true";
		
		return "login.jsp";
	}
	
	@Execute(validator = true, input = "/login", redirect=true)
	public String doLogin() {
		if(!authentication(loginForm.userId, loginForm.password))
			return REDIRECT_LOGIN_PAGE;
		
		Assertion.notNull(loginInfoDto.userId);
		return redirectTo();
	}
	
	private boolean authentication(String userId, String password) {
		Assertion.notNull(userId);
		Assertion.notNull(password);
		
		UserInfo userInfo = userInfoService.findByPasswordAndUserID(userId, password);
		
		if(userInfo == null || StringUtil.isEmpty(userInfo.userId))
			return false;
		
		loginInfoDto.userId = userInfo.userId;
		return true;
	}
	
	private String redirectTo() {
		String loginErrorURI = loginInfoDto.getLoginErrorURI();
		if(StringUtil.isEmpty(loginErrorURI))
			return "/?redirect=true";
		
		loginInfoDto.loginSuccess();
		
		return loginErrorURI;
	}
}